import React, { memo, useEffect, useRef, useCallback, useState } from 'react'
import { useSelector, useDispatch, shallowEqual } from 'react-redux'

import { Carousel } from 'antd';

import { getTopBannersAction } from '../../store/actionCreators'

import {
  BannerWrapper,
  BannerLeft,
  BannerRight,
  BannerControl
} from "./style"

export default memo(function WYTopBanner() {
    // state
  const [currentIndex, setCurrentIndex] = useState(0)

  // 组件和redux关联：1.获取数据(拿到topBanners数据) 2.进行dispatch操作
  const { topBanners } = useSelector(state => ({
    // topBanners: state.get("recommend").get("topBanners")
    // 上面可简写 getIn(可迭代)
    topBanners: state.getIn(["recommend", "topBanners"])
  }), shallowEqual)
   const dispatch = useDispatch()
   
  // 其他hooks
   const bannerRef = useRef()
  // 想要拿到数据 就要发送网络请求
   useEffect(() => {
     dispatch( getTopBannersAction())
   }, [dispatch])  // [dispatch]是一个依赖

   const bannerChange = useCallback((from, to) => {
     setCurrentIndex(to)
   }, [])
    
  // 其他业务逻辑
  const bgImage = topBanners[currentIndex] && (topBanners[currentIndex].imageUrl+"?imageView&blur=40x20")    

    return (
        <BannerWrapper bgImage={bgImage}>
          <div className='banner wrap-v2'>
            <BannerLeft>
            <Carousel effect="fade" autoplay ref={bannerRef} beforeChange={bannerChange}>
              {
                topBanners.map(item => {
                    return (
                      <div className='banner-item' key={item.imageUrl}>
                        <img className='image' src={item.imageUrl} alt={item.typeTitle}/>
                      </div>
                    )
                })
              }
            </Carousel>
            </BannerLeft>
            <BannerRight></BannerRight>
            <BannerControl>
              <button className='btn left' onClick={e => bannerRef.current.prev()}></button>
              <button className='btn right'  onClick={e => bannerRef.current.next()}></button>
            </BannerControl>
          </div>
        </BannerWrapper>
    )
})
